//
//  RegiestDeviceNumber.m
//
//
//  Created by gynjobs on 2017/8/15.
//  Copyright © 2017年 gynjobs. All rights reserved.
//

#import "RegiestDeviceNumber.h"
#import "OpenUDID.h"
#import "LocationManager.h"
static CLLocation *lastLocation = nil;

@implementation RegiestDeviceNumber
/** 注册设备 **/
+(void)regiesterDevice:(void(^)(NSError *error))errorBack {
    [self isAlreadRegiesteredDevice];
    
    //注册的字典
    NSMutableDictionary *regiesterDic = [self getDeviceMessage];
    //开始注册
    [[ClientApi getInstance] registerImei:regiesterDic withCallBack:^(id  _Nullable responseObject, NSError * _Nullable error) {
        
        if(error){
            
            if(errorBack){
                
                errorBack(error);
            }
            
        }else{
            
            id auth_key = [responseObject valueForKey:@"key"];
            id auth_did = [responseObject valueForKey:@"did"];
            
            GYNLog(@" key = %@ -- did = %@",auth_key,auth_did);
            
            id city = [responseObject valueForKey:@"city"];
            
            
            if (auth_key && [auth_key length] > 0) {
                
                [EncryptAction cacheAuthKey:auth_key];
            }
            
            if(auth_did && [auth_did integerValue] > 0){
                
                [EncryptAction cacheAuthDid:auth_did];
            }
            [[CacheHelper getInstance] cacheCityInfo:city];
            
            //[[NotificationManager getInstance] startListen];
            
            if(errorBack){
                
                errorBack(nil);
                
            }
        }
    }];

}
+(BOOL)isAlreadRegiesteredDevice{
    if([[EncryptAction getAuthDid] integerValue] != [AUTH_DID integerValue] && ![[EncryptAction getAuthKey] isEqualToString:AUTH_KEY]){
        
        return YES;
    }
    
    return NO;
}
+(NSMutableDictionary *)getDeviceMessage{
    NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:2];
    
    NSString * imei = [OpenUDID value];//[DeviceUtils getDeviceUUID];
    NSString * name = [GetDeviceMessageTool DeviceUserName];
    NSString * sys_v = [GetDeviceMessageTool DeviceVersion];
    
    
    [dic setValue:OS_TYPE forKey:@"os_type"];
    [dic setValue:imei forKey:@"imei"];
    [dic setValue:name forKey:@"name"];
    [dic setValue:sys_v forKey:@"sys_v"];
    
    if(lastLocation){
        
        NSString * latitude = [NSString stringWithFormat:@"%f",lastLocation.coordinate.latitude];
        NSString * longitude = [NSString stringWithFormat:@"%f",lastLocation.coordinate.longitude];
        [dic setValue:latitude forKey:@"latitude"];
        [dic setValue:longitude forKey:@"longitude"];
    }
    
    
    return dic;

}
@end
